package com.qf.controller;

import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.util.Basedata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;


    @RequestMapping("/register")
    public Basedata register(User user){

        Basedata basedata = new Basedata();
        Integer register = userService.register(user);
        basedata.setCode(register);
        if(register==0){
            basedata.setInfo("账号已被注册");
        }
        return basedata;

    }

    @RequestMapping("/login")
    public Basedata login(User user, HttpSession session){
        User users = userService.login(user.getTel());

        if(users==null){
            return new Basedata(0,"账号不存在");
        } else if(!user.getPassword().equals(users.getPassword())){
            return new Basedata(0,"密码有误");
        }
        session.setAttribute("loginUser",users);
        return new Basedata(1,users);
    }


    @RequestMapping("/updateInfo")
    public Basedata updateInfo(User user,HttpSession httpSession){

        User users = (User)httpSession.getAttribute("loginUser");

        users.setTel(user.getTel());
        users.setEmail(user.getEmail());
        users.setPassword(user.getPassword());

        Integer update = userService.updateInfo(users);

        httpSession.setAttribute("loginUser",users);

        return new Basedata(1,"修改成功");

    }

    @RequestMapping("/checkLogin")
    public Basedata checkLogin(HttpSession httpSession){

        User user = (User)httpSession.getAttribute("loginUser");
        if(user!=null){
            return new Basedata(1,user);
        }
        return new Basedata(0,"请先登录");
    }


}
